
/**
*
* @ author: hxwy
* @ email: 928936715@qq.com
* @ date: 2020-04-13 15:25
*/
export default class Rotation extends Laya.Script3D {

    lastMouseX : number = 0;
    scene:Laya.Scene3D;
    firstTouch : boolean = true;
    gameOver : boolean = false;
    constructor() {
        super();
    }
    init(scene)
    {
        this.scene = scene;
        Laya.stage.on("GameOver",this, function(){this.gameOver = true});
        Laya.stage.on("ContinueGame",this,function(){this.gameOver = false;(this.owner as Laya.Sprite3D).transform.localRotationEulerY = 0});
    }
    onAwake()
    {
        if (Laya.Browser.onPC)
        {
            Laya.stage.on(Laya.Event.MOUSE_DOWN,this,this.MouseDown);
            Laya.stage.on(Laya.Event.MOUSE_UP,this,function()
            {
                Laya.stage.off(Laya.Event.MOUSE_MOVE,this,this.MouseMove);
            });
            Laya.stage.on(Laya.Event.MOUSE_OUT,this,function()
            {
                Laya.stage.off(Laya.Event.MOUSE_MOVE,this,this.MouseMove);
            });
        }
        
    }
    onUpdate()
    {
        if(this.gameOver)return;

        if(!Laya.Browser.onMobile)return;

        if(this.scene.input.touchCount() == 1)
        {
            let tpuch = this.scene.input.getTouch(0);
            if(this.firstTouch)
            {
                this.firstTouch = false;
                this.lastMouseX = tpuch.position.x;
            }
            else
            {
                let delx = tpuch.position.x - this.lastMouseX;
                this.lastMouseX = tpuch.position.x;
                let transform = (this.owner as Laya.MeshSprite3D).transform;
                //P2是否是局部坐标
                transform.rotate(new Laya.Vector3(0,delx/3,0),true,false); 
            }
        }
        else
        {
            this.firstTouch = true;
            this.lastMouseX = 0;
        }
    }

    MouseDown()
    {
        if(this.gameOver)return;

        this.lastMouseX = Laya.stage.mouseX;
        Laya.stage.on(Laya.Event.MOUSE_MOVE,this,this.MouseMove)
    }
    MouseMove()
    {
        if(this.gameOver)return;

        let delx = Laya.stage.mouseX - this.lastMouseX;
        this.lastMouseX = Laya.stage.mouseX;
        let transform = (this.owner as Laya.MeshSprite3D).transform;
        transform.rotate(new Laya.Vector3(0,delx/5,0),true,false);
    }
}
